<?php

class valid
{
	public static function isMobile($val) {
		$reg = '/^1[3456789]\d{9}$/';
		return preg_match($reg, $val);
	}

	public static function isTelphone($val) {
		$reg = '/^((0\d{2,3})-)?(\d{7,8})(-(\d{3,}))?$/';
		return preg_match($reg, $val);
	}

	public static function isMoney($val) {
		$reg1 = '/^[0-9]+$/';
		$reg2 = '/^[0-9]+\.?[0-9]+?$/';
		return preg_match($reg1, $val) || preg_match($reg2, $val);
	}

	public static function isNum($val) {
		$reg = '/^[0-9]+$/';
		return preg_match($reg, $val);
	}

	public static function isWicked($val) {
		$reg = '/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/';
		return preg_match($reg, $val);
	}

	public static function isTime($val) {
		$reg = '/^([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})$/';
		return preg_match($reg, $val);
	}

	public static function isDate($val) {
		$reg = '/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/';
		return preg_match($reg, $val);
	}
}

class util
{
	public static function mustFilter($val) {
		$ra = array
	    (
	        '/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '/script/', '/javascript/', '/vbscript/', 
	        '/expression/', '/applet/', '/meta/', '/xml/', '/blink/', '/link/', '/style/', '/embed/', 
	        '/object/', '/layer/', '/title/', '/bgsound/', '/base/', '/onload/', '/onunload/',
	        '/onchange/', '/onsubmit/', '/onreset/', '/onselect/', '/onblur/', '/onfocus/', '/onabort/', 
	        '/onkeydown/', '/onkeypress/', '/onkeyup/', '/onclick/', '/ondblclick/', '/onmousedown/', 
	        '/onmousemove/', '/onmouseout/', '/onmouseover/', '/onmouseup/', '/onunload/', '/delete/', 
	        '/insert/', '/update/', '/select/', '/\./', '/\//', '/\'/', '/\"/', '/\:/', '/\%/', '/\$/',
            '/\!/', '/\*/', '/\=/', '/\;/'
	    );
	    $val = preg_replace($ra, '', $val);
	    $val = htmlentities(strip_tags($val));
	    return $val;
	}

	public static function isMobileDevice() {
		if (isset($_SERVER['HTTP_X_WAP_PROFILE']))
	        return true;

	    if (isset($_SERVER['HTTP_VIA']) && stristr($_SERVER['HTTP_VIA'], "wap"))
	        return true;

	    $user_agent = $_SERVER['HTTP_USER_AGENT'];
	    $mobile_agents = array
	    (
	        'iphone','android','phone','mobile','wap','netfront','java','opera mobi',
	        'opera mini','ucweb','windows ce','symbian','series','webos','sony','blackberry','dopod',
	        'nokia','samsung','palmsource','xda','pieplus','meizu','midp','cldc','motorola','foma',
	        'docomo','up.browser','up.link','blazer','helio','hosin','huawei','novarra','coolpad',
	        'techfaith','alcatel','amoi','ktouch','nexian','ericsson','philips','sagem','wellcom',
	        'bunjalloo','maui','smartphone','iemobile','spice','bird','zte-','longcos','pantech',
	        'gionee','portalmmm','jig browser','hiptop','benq','haier','^lct','320x320','240x320',
	        '176x220','windows phone','cect','compal','ctl','lg','nec','tcl','daxian','dbtel','eastcom',
	        'konka','kejian','lenovo','mot','soutec','sgh','sed','capitel','panasonic','sonyericsson',
	        'sharp','panda','zte','acer','acoon','acs-','abacho','ahong','airness','anywhereyougo.com',
	        'applewebkit/525','applewebkit/532','asus','audio','au-mic','avantogo','becker','bilbo',
	        'bleu','cdm-','danger','elaine','eric','etouch','fly ','fly_','fly-','go.web','goodaccess',
	        'gradiente','grundig','hedy','hitachi','htc','hutchison','inno','ipad','ipaq','ipod',
	        'jbrowser','kddi','kgt','kwc','lg ','lg2','lg3','lg4','lg5','lg7','lg8','lg9','lg-','lge-',
	        'lge9','maemo','mercator','meridian','micromax','mini','mitsu','mmm','mmp','mobi','mot-',
	        'moto','nec-','newgen','nf-browser','nintendo','nitro','nook','obigo','palm','pg-',
	        'playstation','pocket','pt-','qc-','qtek','rover','sama','samu','sanyo','sch-','scooter',
	        'sec-','sendo','sgh-','siemens','sie-','softbank','sprint','spv','tablet','talkabout',
	        'tcl-','teleca','telit','tianyu','tim-','toshiba','tsm','utec','utstar','verykool','virgin',
	        'vk-','voda','voxtel','vx','wellco','wig browser','wii','wireless','xde','pad','gt-p1000'
	    );

	    $is_mobile = false;
	    foreach ($mobile_agents as $device) {
	        if (stristr($user_agent, $device)) {
	            $is_mobile = true;
	            break;
	        }
	    }
	    return $is_mobile;
	}

	public static function getArrayValue($index, $list) {
	    return $list[$index];
	}

	public static function getListPage($count, $linage) {
		$allpages = 0;

		if ($count <= $linage) {
	    	$allpages = 1;
	    }
	    else if ($count % $linage) {
	    	$allpages = floor($count / $linage) + 1;
	    }
	    else {
	    	$allpages = $count / $linage;
	    }

		return $allpages;
	}

	public static function getRandomNum($len) {
		$min = pow(10 , ($len - 1));
		$max = pow(10, $len) - 1;
		return mt_rand($min, $max);
	}

	public static function getValidError($tip) {
		$result = array();
		$result['res'] = -1;
    	$result['msg'] = 'ERROR：' . $tip;
    	return $result;
	}

	public static function getDataError($tip) {
		$result = array();
		$result['res'] = -2;
    	$result['msg'] = 'ERROR：' . $tip;
    	return $result;
	}

	public static function getWarnTip($tip) {
		$result = array();
		$result['res'] = -3;
    	$result['msg'] = 'WARN：' . $tip;
    	return $result;
	}

	public static function getVisitError($tip) {
		$result = array();
		$result['res'] = -500;
    	$result['msg'] = 'ERROR：' . $tip;
    	return $result;
	}

	public static function getSuccess($tip) {
		$result = array();
		$result['res'] = 1;
    	$result['msg'] = $tip;
    	return $result;
	}

	public static function writeLog($val) {
		$year = date('Y');
		$month = date('m');
		$today = date('Y-m-d');
		$time = date('Y-m-d H:i:s');
		$time .= ' -> ';
		$ip = util::getIP() . ', ';
		$val = $time . $ip . $val . "\r\n";

		$folder = _LOGS_PATH_ . 'log/' . $year . '/' . $month;
		if (!is_dir($folder)) {
			mkdir(iconv('UTF-8', 'GBK', $folder), 0777, true);
		}

		$path = $folder . '/' . $today . '.log';
		$file = fopen($path, 'a');

		fwrite($file, $val);
		fclose($file);
	}

	public static function httpPost($url, $data = null) {
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_TIMEOUT, 500);
		curl_setopt($curl, CURLOPT_URL, $url);

		if (!empty($data)) {
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}

		$res = curl_exec($curl);
		curl_close($curl);

		return $res;
	}

	public static function httpGet($url) {
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_TIMEOUT, 500);
		curl_setopt($curl, CURLOPT_URL, $url);

		$res = curl_exec($curl);
		curl_close($curl);

		return $res;
	}

	public static function encrypt($txt, $key = '') {
		$txt = $txt . $key;
	    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
	    //$nh = rand(0, 64);
	    $nh = 18;
	    $ch = $chars[$nh];
	    $mdKey = md5($key . $ch);
	    $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7);
	    $txt = base64_encode($txt);
	    $tmp = '';
	    $i = 0; $j = 0; $k = 0;
	    for ($i = 0; $i < strlen($txt); $i++) {
	        $k = $k == strlen($mdKey) ? 0 : $k;
	        $j = ($nh + strpos($chars, $txt[$i]) + ord($mdKey[$k++])) % 64;
	        $tmp .= $chars[$j];
	    }
	    return urlencode(base64_encode($ch . $tmp));
	}

	public static function decrypt($txt, $key = '') {
		if (empty($txt)) {
			return '';
		}
		
		$txt = base64_decode(urldecode($txt));
	    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
	    $ch = $txt[0];
	    $nh = strpos($chars, $ch);
	    $mdKey = md5($key . $ch);
	    $mdKey = substr($mdKey , $nh % 8, $nh % 8 + 7);
	    $txt = substr($txt, 1);
	    $tmp = '';
	    $i = 0; $j = 0; $k = 0;
	    for ($i = 0; $i < strlen($txt); $i++) {
	        $k = $k == strlen($mdKey) ? 0 : $k;
	        $j = strpos($chars, $txt[$i]) - $nh - ord($mdKey[$k++]);
	        while ($j < 0) {
	        	$j += 64;
	        }
	        $tmp .= $chars[$j];
	    }
	    return trim(base64_decode($tmp), $key);
	}

	public static function getUUID($prefix = '') {
	    $uid = uniqid('', true);
	    $data = $prefix;
	    $data .= time();
	    $data .= isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : '';
	    $data .= isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
	    $data .= isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
	    $data .= isset($_SERVER['REMOTE_PORT']) ? $_SERVER['REMOTE_PORT'] : '';
	    $hash = strtoupper(hash('ripemd128', $uid . md5($data)));
	    return $hash;
	}

	public static function getFileName($fileBase64) {
		if (empty($fileBase64)) {
			return '';
		}
		if (strpos($fileBase64, ';base64,') === false) {
			return false;
		}

		$base64 = explode(';base64,', $fileBase64);
		$base64[0] = str_replace('data:', '', $base64[0]);
		$fileName = util::getUUID();

		switch ($base64[0]) {
			case 'image/jpeg':
				$fileName .= '.jpg';
				break;
			case 'image/png':
				$fileName .= '.png';
				break;
	        case 'application/vnd.ms-excel':
	            $fileName .= '.xls';
	            break;
	        case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
	            $fileName .= '.xlsx';
	            break;
	        case 'application/msword':
	            $fileName .= '.doc';
	            break;
	        default:
	            $fileName .= '.jpg';
		}

		return $fileName;
	}

	public static function saveFile($fileBase64, $filePath) {
		$base64 = explode(';base64,', $fileBase64);
		$file = base64_decode($base64[1]);
		file_put_contents($filePath, $file);
	}

	public static function deleteFile($filePath) {
		if (file_exists($filePath)) {
			unlink($filePath);
		}
	}

	public static function writeFile($path, $filename, $val) {
		$folder = _FILE_PATH_ . $path;
		if (!is_dir($folder)) {
			mkdir(iconv('UTF-8', 'GBK', $folder), 0777, true);
		}

		$path = $folder . '/' . $filename;
		$file = fopen($path, 'w');

		fwrite($file, $val);
		fclose($file);
	}

	public static function readFile($path) {
		$html = '';
		if (file_exists($path)) {
			if (($fp = fopen($path, 'a+')) != false) {
				$html = fread($fp, filesize($path));
				//$html = str_replace("rn", "<br/>", $html);
			}
		}

		return $html;
	}

	public static function getIP() {
		$realip = '';
		if (isset($_SERVER)) {
			if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
				$realip = $_SERVER['HTTP_X_FORWARDED_FOR'];
			}
			else if (isset($_SERVER['HTTP_CLIENT_IP'])) {
				$realip = $_SERVER['HTTP_CLIENT_IP'];
			}
			else {
				$realip = $_SERVER['REMOTE_ADDR'];
			}
		}
		else {
			if (getenv('HTTP_X_FORWARDED_FOR')) {
				$realip = getenv('HTTP_X_FORWARDED_FOR');
			}
			else if (getenv('HTTP_CLIENT_IP')) {
				$realip = getenv('HTTP_CLIENT_IP');
			}
			else {
				$realip = getenv('REMOTE_ADDR');
			}
		}

		return $realip;
	}

	public static function getOperateItem($menuid) {
		$token = util::decrypt($_SERVER['HTTP_TOKEN']);
		$temp = explode('[@#%&]', $token);

		$item = array();

		$rst = new sqlcon();
		$list = $rst->getList('b.code', 'user a, operate b', "a.roleid = b.roleid and b.type = 'role' and a.userid = '" . $temp[0] . "' and b.menuid = '" . $menuid . "'");
		for ($i = 0; $i < count($list); $i++) {
			$item[$list[$i]['code']] = 'yes';
		}

		return $item;
	}
}